<template>
  <div class="classroom-selector">
    <div class="header-container">
      <h1 class="title">教室查询系统</h1>
      <div class="tip-box">
        <p class="tip-content">
          📌 注意：本页查询的教室基于教务处课表与调课信息，仅支持系部教室查询，其他教室请以教务系统查询为准。
        </p>
      </div>
    </div>

    <el-form
        :model="form"
        label-width="120px"
        ref="formRef"
        :rules="rules"
        class="query-form"
    >
      <el-form-item label="学年学期:" prop="schoolTerm">
        <el-input
            v-model="form.schoolTerm"
            placeholder="自动检测或手动输入"
            class="custom-input"
        >
          <template #prefix>
            <el-icon>
              <Calendar/>
            </el-icon>
          </template>
        </el-input>
      </el-form-item>

      <el-form-item label="第几周:" prop="week">
        <el-input
            v-model="form.week"
            placeholder="例：1 或 1,2,3 或 3-9"
            class="custom-input"
        >
          <template #prefix>
            <el-icon>
              <Date/>
            </el-icon>
          </template>
        </el-input>
      </el-form-item>

      <el-form-item label="星期/节次:" prop="dayPeriod">
        <el-input
            v-model="form.dayPeriod"
            placeholder="例：三/3-4 或 三/3 或 四/3-4,五/6-7"
            class="custom-input"
        >
          <template #prefix>
            <el-icon>
              <Time/>
            </el-icon>
          </template>
        </el-input>
      </el-form-item>

      <el-form-item>
        <el-button
            type="primary"
            @click="getAvailableRooms"
            :loading="check_loading"
            class="search-btn"
        >
          <span v-if="!check_loading">查询可用教室</span>
          <span v-else>
            <el-icon><Loading/></el-icon>
            查询中...
          </span>
        </el-button>
      </el-form-item>
    </el-form>

    <div class="result-container">
      <div v-if="availableRooms.length > 0" class="result-list">
        <h3 class="result-title">可用教室列表</h3>
        <ul>
          <li v-for="room in availableRooms" :key="room" class="room-item">
            <el-icon>
              <Location/>
            </el-icon>
            {{ room }}
          </li>
        </ul>
      </div>
      <div v-else class="empty-state">
        <el-empty
            :image-size="150"
            description="暂无可用教室"
            class="empty-content"
        >
          <el-button
              type="text"
              @click="resetForm"
              class="reset-btn"
          >
            重置查询条件
          </el-button>
        </el-empty>
      </div>
    </div>
  </div>
</template>
<script setup>
import {ref, reactive, onMounted} from 'vue';
import {ElForm, ElFormItem, ElInput, ElButton, ElMessage} from 'element-plus';
import {jsonApi} from "@/global.js";

const formRef = ref(null);
const check_loading = ref(false);

// 表单数据模型
const form = reactive({
  schoolTerm: '',
  week: '',
  dayPeriod: ''
});

// 可用教室列表
const availableRooms = ref([]);

// 校验规则
const rules = reactive({
  schoolTerm: [
    {required: true, message: '学年学期不能为空', trigger: 'blur'},
    {
      pattern: /^(20\d{2}-20\d{2})学年(秋|春)季学期$/,
      message: '请输入正确的格式，如：2024-2025学年秋季学期',
      trigger: 'blur'
    }
  ],
  week: [
    {required: true, message: '周次不能为空', trigger: 'blur'},
    {
      validator: (rule, value, callback) => {
        const regex = /^(\d{1,2})(-(\d{1,2}))?$/;
        const parts = value.split(',').map(item => item.trim());

        for (const part of parts) {
          if (!regex.test(part)) {
            return callback(new Error('周次格式错误，请输入类似 1 或 1,2,3 或 3-9'));
          }

          const [start, end] = part.split('-').map(Number);
          if (start < 1 || start > 20 || (end && (end < 1 || end > 20 || start >= end))) {
            return callback(new Error('周次范围错误，必须在 1-20 之间且起始周小于结束周'));
          }
        }

        callback();
      },
      trigger: 'blur'
    }
  ],
  dayPeriod: [
    {required: true, message: '星期/节次不能为空', trigger: 'blur'},
    {
      validator: (rule, value, callback) => {
        const regex = /^(一|二|三|四|五|六|日)\/(\d{1,2}(-\d{1,2})?)(,(一|二|三|四|五|六|日)\/(\d{1,2}(-\d{1,2})?))*$/;

        if (!regex.test(value)) {
          return callback(new Error('格式错误，请按照 星期/节次 格式，例：三/3-4 或 三/3 或 四/3-4,五/6-7'));
        }

        const periods = value.split(',').map(item => item.trim());
        for (const period of periods) {
          const [day, sessionPart] = period.split('/');
          const sessions = sessionPart.split('-').map(Number);

          if (sessions.length === 1) {
            const session = sessions[0];
            if (session < 1 || session > 13) {
              return callback(new Error('节次范围错误，必须在 1-13 之间'));
            }
          } else if (sessions.length === 2) {
            const [startSession, endSession] = sessions;
            if (
                startSession < 1 ||
                endSession > 13 ||
                startSession >= endSession
            ) {
              return callback(new Error('节次范围错误，必须在 1-13 之间且起始节次小于结束节次'));
            }
          }
        }

        callback();
      },
      trigger: 'blur'
    }
  ]
});


function getSchoolTerm(date) {
  const currentYear = date.getFullYear();
  const currentMonth = date.getMonth() + 1;

  let startYear, endYear;
  if (currentMonth >= 8 || currentMonth <= 1) {
    startYear = currentYear;
    endYear = currentYear + 1;
  } else {
    startYear = currentYear - 1;
    endYear = currentYear;
  }

  let term = currentMonth >= 2 && currentMonth <= 7 ? '春季学期' : '秋季学期';

  return `${startYear}-${endYear}学年${term}`;
}

async function getAvailableRooms() {
  try {
    check_loading.value = true;
    const body = {
      "term": form.schoolTerm,
      "week": form.week,
      "new_class_time": form.dayPeriod
    };
    const respond = await jsonApi('/teachingarrangementmanagement/can_use_classroom/', JSON.stringify(body));
    const roomsData = await respond.json();
    availableRooms.value = roomsData['can_use_room'];
    check_loading.value = false;
  } catch (e) {
    ElMessage.error('获取教室列表失败: ' + e);
    check_loading.value = false;
  }
}

onMounted(() => {
  form.schoolTerm = getSchoolTerm(new Date());
});
</script>

<style scoped>
.classroom-selector {
  max-width: 800px;
  margin: 2rem auto;
  padding: 2rem;
  background: #fff;
  border-radius: 16px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
  transition: transform 0.3s ease;
}

.header-container {
  text-align: center;
  margin-bottom: 2.5rem;
}

.title {
  color: #2c3e50;
  font-size: 2.5rem;
  margin-bottom: 1rem;
  font-weight: 600;
}

.tip-box {
  background: #f8f9fa;
  padding: 1rem;
  border-radius: 8px;
  display: inline-block;
}

.tip-content {
  color: #6c757d;
  margin: 0;
  font-size: 0.9rem;
}

.query-form {
  background: #f8f9fa;
  padding: 2rem;
  border-radius: 12px;
  margin-bottom: 2rem;
}

.custom-input {
  transition: all 0.3s ease;
}

.custom-input:focus {
  border-color: #409eff;
  box-shadow: 0 0 8px rgba(64, 158, 255, 0.2);
}

.search-btn {
  width: 100%;
  height: 48px;
  font-size: 1.1rem;
  letter-spacing: 1px;
  transition: all 0.3s ease;
}

.search-btn:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(64, 158, 255, 0.3);
}

.result-container {
  background: #fff;
  border-radius: 12px;
  padding: 2rem;
}

.result-title {
  color: #409eff;
  font-size: 1.25rem;
  margin-bottom: 1.5rem;
  border-bottom: 2px solid #ebeef5;
  padding-bottom: 0.8rem;
}

.room-item {
  padding: 1rem;
  margin: 0.5rem 0;
  background: #f8f9fa;
  border-radius: 8px;
  display: flex;
  align-items: center;
  transition: all 0.3s ease;
}

.room-item:hover {
  background: #ebedf0;
  transform: translateX(8px);
}

.empty-state {
  text-align: center;
  padding: 3rem 0;
}

.empty-content {
  margin: 2rem 0;
}

.reset-btn {
  color: #409eff;
  font-weight: 500;
  margin-top: 1rem;
  display: inline-block;
}
</style>